#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QCoreApplication::setOrganizationName("Team16");
    QCoreApplication::setOrganizationDomain("team16.ru");
    QCoreApplication::setApplicationName("psx4m-gui");


    settings=new QSettings();

    fps_show=settings->value("fps-show",false).toBool();
    cycle=settings->value("cycle",1).toInt();
    frameskiping=settings->value("frame-skipping",0).toInt();
    save_slot=settings->value("saveslot",0).toInt();

    abbey=settings->value("abbey",false).toBool();
    logged=settings->value("logged",false).toBool();
    fscreen=settings->value("fullscreen",false).toBool();
    accel=settings->value("accel",false).toBool();

    path = settings->value("rom-path","/home/user/MyDocs").toString();

    QDir dir(path);
         dir.setFilter(QDir::Files);
         dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList()<<"*.bin"<<"*.iso"<<"*.img");

         QFileInfoList list = dir.entryInfoList();
         int o=0;
         for (int i = 0; i < list.size(); ++i) {
             QFileInfo fileInfo = list.at(i);
             if (fileInfo.fileName()=="scph1001.bin")continue;
             ui->listWidget->addItem(new QListWidgetItem(fileInfo.fileName()));
             roms.insert(o++,fileInfo.absoluteFilePath());
         }
         connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(runGame()));
connect(ui->listWidget,SIGNAL(currentTextChanged(QString)),this,SLOT(currentTextChanged(QString)));


         QMenu *fsk=new QMenu(tr("Frameskip"));
         QActionGroup *gr=new QActionGroup(fsk);
         for (int i=-1;i<=8;i++){
QString nam=QString("%1").arg(i);
if (i==-1)nam="Auto";
if (i==0)nam="Off";
             QAction *nm=fsk->addAction(nam,this,SLOT(fm_skip_ch()));
             nm->setActionGroup(gr);
             nm->setCheckable(true);
             if (i==frameskiping)nm->setChecked(true);
framem.append(nm);
         }



         QActionGroup *gr2=new QActionGroup(fsk);

         QMenu *cml=new QMenu(tr("Cycle multiplier"));
         for (int i=0;i<=10;i++){
             QAction *nm=cml->addAction(QString("%1").arg(i),this,SLOT(cml_ch()));
             nm->setActionGroup(gr2);
             nm->setCheckable(true);
             if (i==cycle)nm->setChecked(true);
             cyclem.append(nm);
         }


         QActionGroup *gr3=new QActionGroup(fsk);

         QMenu *sav=new QMenu(tr("Save slot"));
         for (int i=0;i<=5;i++){
             QAction *nm=sav->addAction(QString("%1").arg(i),this,SLOT(cml_ch()));
             nm->setActionGroup(gr3);
             nm->setCheckable(true);
             if (i==save_slot)nm->setChecked(true);
         }

         QMenu *extra=new QMenu(tr("Extra"));
        /* ldbg=new QAction(tr("Create debug log"),&opt);
         ldbg->setCheckable(true);
         ldbg->setChecked(logged);*/

        // extra->addAction(tr("Show log"),this,SLOT(show_log()));


         fpsm=new QAction(tr("Show FPS"),&opt);
         fpsm->setCheckable(true);
         fpsm->setChecked(fps_show);

         eas=new QAction(tr("Exit after start"),&opt);
         eas->setCheckable(true);
         eas->setChecked(settings->value("exit",true).toBool());


        fscr=new QAction(tr("Fullscreen"),&opt);
        fscr->setCheckable(true);
        fscr->setChecked(fscreen);

        accelm=new QAction(tr("Accelometer"),&opt);
        accelm->setCheckable(true);
        accelm->setChecked(accel);

         abbm=new QAction(tr("Abe's Oddysee Fix"),&opt);
         abbm->setCheckable(true);
         abbm->setChecked(abbey);
         extra->addAction(abbm);
         extra->addAction(eas);





         opt.addMenu(fsk);
         opt.addMenu(cml);
         opt.addMenu(sav);
         opt.addMenu(extra);

         extra->addAction(tr("Select directory"),this,SLOT(select_dir()));

         ui->checkBox->setChecked(settings->value("nosound",false).toBool());


        this->menuBar()->addAction(tr("Options"),&opt,SLOT(show()));
        //this->menuBar()->addAction(tr("Report a bug"),this,SLOT(bug()));
        this->menuBar()->addAction(tr("About"),this,SLOT(about()));




        this->setWindowTitle("PSX4M-Gui");
       if (!QFile("/home/opt/psx4m/keys").exists()){
           system ("mkdir -p /home/opt/psx4m");
           QMessageBox msg;
           msg.setText(tr("You should set keys to use psx4m"));
           msg.exec();
           QFile file("/opt/psx4m/keys");
           if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
               QMessageBox msg2;
               msg2.setText(tr("Fatal error, check permission of file /home/opt/psx4m/keys"));
               msg2.exec();
               qApp->exit(1);
               return ;
           }else
           {

               file.close();
               keyopt=new keys(this);
               keyopt->exec();
           }

       }else{
           keyopt=new keys(this);
       }
       this->menuBar()->addAction(tr("Configure keys"),keyopt,SLOT(exec()));
       //this->menuBar()->addAction(ldbg);
       this->menuBar()->addAction(fpsm);
       this->menuBar()->addAction(fscr);
       this->menuBar()->addAction(accelm);
}
/*
void MainWindow::show_log(){
    QDialog dg;
    QString text=tr("Log file from psx4m<br />");
    QFile file("/opt/psx4m/log");
         if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
             return;

         QTextStream in(&file);
         while (!in.atEnd()) {
             QString line = in.readLine();
             text+=line+"<br />";
         }


     QHBoxLayout *fg=new QHBoxLayout(&dg);


    QTextEdit t(QString(text),&dg);
fg->addWidget(&t);


    QAbstractKineticScroller *scroller =t.property("kineticScroller").value<QAbstractKineticScroller *>();
    scroller->setEnabled(true);

     dg.exec();
}*/

/*void MainWindow::bug(){

    QMessageBox msg;
    msg.setText(tr("Copy last log file to clipboard?"));
    msg.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
    int ret=msg.exec();
    QString text="";
    if (ret==QMessageBox::Yes){
        QFile file("/opt/psx4m/log");
             if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
                 QMessageBox msg2;
                 msg2.setText(tr("Can't open log file"));
                 msg2.exec();
                 goto toEnd;
             }

             QTextStream in(&file);
             text=in.readAll();
             QClipboard *clipboard = QApplication::clipboard();
             clipboard->setText(text);
    }
    toEnd:
    QDesktopServices::openUrl(QUrl("http://code.google.com/p/psx4m/issues/entry"));
}*/

void MainWindow::about(){
    QDialog dg;
    QString text=tr("<h3>Psx4m</h3>"\
                    "Project creator: smoku<br />" \
                    "Active developer: bonapart (icq:175256)<br />" \
                    "Project homepage: <a href='http://psx4m.googlecode.com'>psx4m.googlecode.com</a><br />" \
                    "Project bugtracker: <a href='http://code.google.com/p/psx4m/issues/'>code.google.com/p/psx4m/issues/</a><br />");


    QScrollArea tu(&dg);
     QHBoxLayout *fg=new QHBoxLayout(&dg);
     fg->addWidget(&tu);

    QLabel t(QString(text),&tu);
    t.setTextInteractionFlags(Qt::LinksAccessibleByMouse);
    tu.setWidget(&t);


    dg.exec();
}

void MainWindow::currentTextChanged ( const QString & currentText ){
    cycle=settings->value(QString("cycle[%1]").arg(currentText),0).toInt();
    frameskiping=settings->value(QString("frame-skipping[%1]").arg(currentText),0).toInt();
cyclem.at(cycle)->setChecked(true);
framem.at(frameskiping+1)->setChecked(true);
}

void MainWindow::select_dir(){
    QString dir;
   QString directory=QFileDialog::getExistingDirectory(this,tr("Select directory"),dir,QFileDialog::ShowDirsOnly);
   if (!directory.isEmpty()){
       path =  directory;
       settings->setValue("rom-path",path);
   ui->listWidget->clear();
   roms.clear();
       QDir dir(path);
            dir.setFilter(QDir::Files);
            dir.setSorting(QDir::Name);
   dir.setNameFilters(QStringList()<<"*.bin"<<"*.iso"<<"*.img");

            QFileInfoList list = dir.entryInfoList();
            int o=0;
            for (int i = 0; i < list.size(); ++i) {
                QFileInfo fileInfo = list.at(i);
                if (fileInfo.fileName()=="scph1001.bin")continue;
                ui->listWidget->addItem(new QListWidgetItem(fileInfo.fileName()));
                roms.insert(o++,fileInfo.absoluteFilePath());
            }
   }
}

void MainWindow::save_ch(){
    QAction *action = qobject_cast<QAction *>(sender());
    save_slot=action->text().toInt();
    settings->setValue("saveslot",save_slot);
}

void MainWindow::fm_skip_ch(){
    QAction *action = qobject_cast<QAction *>(sender());
    frameskiping=action->text().toInt();
    if (action->text()=="Auto")frameskiping=-1;
    if (action->text()=="Off")frameskiping=0;
    if (ui->listWidget->currentRow()==-1)
    settings->setValue("frame-skipping",frameskiping);
    else
    settings->setValue(QString("frame-skipping[%1]").arg(ui->listWidget->currentItem()->text()) ,frameskiping);
}
void MainWindow::cml_ch(){
    QAction *action = qobject_cast<QAction *>(sender());
    cycle=action->text().toInt();

    if (ui->listWidget->currentRow()==-1)
    settings->setValue("cycle",cycle);
    else
    settings->setValue(QString("cycle[%1]").arg(ui->listWidget->currentItem()->text()) ,cycle);
}

void MainWindow::runGame(){
    if (!QFile("/home/user/MyDocs/scph1001.bin").exists()){
        QMessageBox msg;
        msg.setText(tr("Error! No bios found\nPut your bios at /home/user/MyDocs/scph1001.bin"));
        msg.exec();
        return;
    }

    if (ui->listWidget->currentRow()==-1){
        QMessageBox msg;
        msg.setText(tr("No rom selected"));
        msg.exec();
        return;}

    QString file=roms.value(ui->listWidget->currentRow());



QString program = "/opt/maemo/usr/games/psx4m";
QStringList arguments;
QProcess *myProcess = new QProcess();

arguments << "-runcd"<<"-load"<<QString("%1").arg(save_slot);




if (frameskiping>0)arguments<<"-frameskip"<<QString("%1").arg(frameskiping);
if (frameskiping==-1)arguments<<"-autoskip";
if (cycle!=0)arguments<<"-cyclemult"<<QString("%1").arg(cycle);

if (ui->checkBox->isChecked())arguments<<"-nosound";
if (fpsm->isChecked())arguments<<"-showfps";
if (abbm->isChecked())arguments<<"-abbeyfix";
if (fscr->isChecked())arguments<<"-fullscreen";
if (accelm->isChecked())arguments<<"-accel";

/*if (ldbg->isChecked()){
    arguments<<"-psxout";
    myProcess->setStandardOutputFile("/opt/psx4m/log");

}*/


arguments<<file;
qDebug(QString("starting %1 %2").arg(program).arg(arguments.join(" ")).toAscii());


myProcess->startDetached(program, arguments,"/home/user/");
if (eas->isChecked())qApp->quit();
}

MainWindow::~MainWindow()
{
    settings->setValue("nosound",ui->checkBox->isChecked());
    settings->setValue("showfps",fpsm->isChecked());
    settings->setValue("abbey",abbm->isChecked());
   // settings->setValue("logged",ldbg->isChecked());
    settings->setValue("fullscreen",fscr->isChecked());
    settings->setValue("exit",eas->isChecked());
    settings->setValue("accel",accelm->isChecked());
    settings->sync();
    delete ui;
}
